package com.aaa.outbound.controller;



import com.aaa.entity.outbound.*;
import com.aaa.entity.stock.Stock;
import com.aaa.entity.system.User;
import com.aaa.outbound.feign.StockFeign;
import com.aaa.outbound.feign.SystemFeign;
import com.aaa.outbound.service.*;
import com.aaa.util.JwtUtils;
import com.aaa.vo.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wjf
 * @since 2020-11-23
 */
@RestController
@RequestMapping("/outbound/outorder")
public class OutorderController {
    @Autowired
    private OutorderService outorderService;
    @Autowired
    private PicktaskService picktaskService;
    @Autowired
    private PicktaskOutorderService picktaskOutorderService;
    @Autowired
    private OutorderDetailService outorderDetailService;
    @Autowired
    private StockFeign stockFeign;
    @Autowired
    private PicktaskDetailService picktaskDetailService;
    @Autowired
    private PicktaskLockDetailService picktaskLockDetailService;
    @Autowired
    private SystemFeign systemFeign;

    @PostMapping("searchOutOrder/{page}/{limit}")
    @ApiOperation("分页查询")
    public R searchOutOrder(@ApiParam("页数")@PathVariable Integer page,
                              @ApiParam("一页几条几条数据")@PathVariable Integer limit,
                              @ApiParam("查询条件封装类")@RequestBody Outorder outorder){
        Page<Outorder> pageinfo=outorderService.searchOutOrder(page,limit,outorder);
        if (pageinfo==null){
            return R.error().message("没有查到数据");
        }
        return R.ok().data("outorder",pageinfo).message("查询成功").code(200);
    }

    @PostMapping("findState")
    @ApiOperation(value = "状态下拉框查询")
    public R findState(){
        List<Map> state = outorderService.findState();
        return R.ok().data("state",state);
    }

    @PostMapping("findCity")
    @ApiOperation(value = "省市级联查")
    public List<Map> findCity(){
        return outorderService.findCity();
    }

    @PostMapping("addOutOrder")
    @ApiOperation(value = "新增出库订单")
    public R addOutOrder(@RequestBody Outorder outorder, HttpServletRequest request){
        Date now=new Date();
        outorder.setCreatetime(now);
        String token = request.getHeader("token");
        Long userid = JwtUtils.getMemberIdByJwtToken(token);
        User user = systemFeign.selectUserById(userid);
        outorder.setCreator(user.getName());
        outorderService.addOutOrder(outorder);
        return R.ok().message("新增成功").code(200);
    }

    @PostMapping("delOutOrder/{outorderno}")
    @ApiOperation(value = "删除出库订单")
    public R delOutOrder(@ApiParam(value = "出库订单号")@PathVariable String outorderno){
        QueryWrapper<Outorder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("outorderno",outorderno);
        Outorder outorder = outorderService.getOne(queryWrapper);
        if (outorder.getState().equals("0")||outorder.getState().equals("9")) {
            outorderService.remove(queryWrapper);
            return R.ok().message("删除成功").code(200);
        }else if (outorder.getState().equals("1")){
            return R.error().message("该订单待审核");
        }else if (outorder.getState().equals("2")) {
            return R.error().message("该订单已审核");
        }else if (outorder.getState().equals("3")) {
            return R.error().message("该订单已分配");
        }else if (outorder.getState().equals("4")) {
            return R.error().message("该订单拣货中");
        }else if (outorder.getState().equals("5")) {
            return R.error().message("该订单已出库");
        }else {
            return R.error().message("系统异常");
        }
    }

    @PostMapping("updateOutOrder")
    @ApiOperation(value = "修改出库订单")
    public R updateOutOrder(@ApiParam(value = "传入包装类") @RequestBody Outorder outorder,HttpServletRequest request){
        String token = request.getHeader("token");
        Long userid = JwtUtils.getMemberIdByJwtToken(token);
        User user = systemFeign.selectUserById(userid);
        outorder.setUpdator(user.getName());
        outorderService.updateById(outorder);
        return R.ok().message("修改成功").code(200);
    }

    //审核
    @PostMapping("checkOutOrder/{outorderno}")
    @ApiOperation(value = "审核出库订单")
    public R checkOutOrder(@ApiParam(value = "出库订单编号")@PathVariable("outorderno") String outorderno){
        QueryWrapper<Outorder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("outorderno",outorderno);
        Outorder outorder = outorderService.getOne(queryWrapper);
        if(outorder.getState().equals("1")) {
            Integer category = outorder.getCategory();
            QueryWrapper<OutorderDetail> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("outorderno", outorderno);
            List<OutorderDetail> list1 = outorderDetailService.list(queryWrapper1);
            for (int i = 0; i < category; i++) {
                Integer uqty = stockFeign.selectSumUqtyByCommoditybar(list1.get(i).getCommoditybar(), 41L);
                int qty = list1.get(i).getQty();
                if (uqty < qty) {
                    return R.error().message("库存不足,请通知相关人员补货");
                } else {
                    continue;
                }
            }
            outorder.setState("2");
            Date now = new Date();
            outorder.setUpdatetime(now);
            outorderService.updateById(outorder);
            return R.ok().message("审核成功").code(200);
        }else {
            return R.error().message("该订单不在待审核状态");
        }
    }

    @PostMapping("cancelCheckOutOrder/{outorderno}")
    @ApiOperation(value = "撤销审核")
    public R cancelCheckOutOrder(@ApiParam(value = "出库订单号")@PathVariable("outorderno") String outorderno){
        QueryWrapper<Outorder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("outorderno",outorderno);
        Outorder outorder = outorderService.getOne(queryWrapper);
        if(outorder.getState().equals("2")) {
            outorder.setState("1");
            outorderService.updateById(outorder);
            return R.ok().message("撤销审核成功").code(200);
        }else {
            return R.error().message("该订单不在已审核状态");
        }
    }


    //分配
    @PostMapping("assignOutOrder/{outorderno}")
    @ApiOperation(value = "生成拣货任务")
    public R assignOutOrder(@ApiParam(value = "出库订单编号")@PathVariable("outorderno") String outorderno,HttpServletRequest request){
        QueryWrapper<Outorder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("outorderno",outorderno);
        Outorder outorder = outorderService.getOne(queryWrapper);
        if (outorder.getState().equals("2")){
            Integer category = outorder.getCategory();
            QueryWrapper<OutorderDetail> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("outorderno",outorderno);
            List<OutorderDetail> list1 = outorderDetailService.list(queryWrapper1);
            for(int i=0;i<category;i++){
                int qty = list1.get(i).getQty();
                List<Stock> stocks = stockFeign.selectStockByCommoditybar(list1.get(i).getCommoditybar(),41L);
                for (Stock stock : stocks) {
                    if(stock.getLocatorcode().equals("111")){
                        continue;
                    }else {
                        if (stock.getUqty() >= qty) {
                            stock.setUqty(stock.getUqty() - qty);
                            stock.setLqty(stock.getLqty() + qty);
                            Date now = new Date();
                            stock.setUpdatetime(now);
                            stockFeign.updateById(stock);
                            PicktaskDetail picktaskDetail = new PicktaskDetail();
                            picktaskDetail.setPid(outorder.getId());
                            picktaskDetail.setStockid(stock.getId());
                            picktaskDetail.setCommodityid(stock.getCommodityid());
                            picktaskDetail.setCommoditybar(stock.getCommoditybar());
                            picktaskDetail.setCommodityname(stock.getCommodityname());
                            picktaskDetail.setLocatorid(stock.getLocatorid());
                            picktaskDetail.setLocatorcode(stock.getLocatorcode());
                            picktaskDetail.setLocatorname(stock.getLocatorname());
                            picktaskDetail.setQty(qty);
                            picktaskDetailService.saveOrUpdate(picktaskDetail);
                            //qty = 0;
                            break;
                        } else {
                            stock.setLqty(stock.getLqty() + stock.getUqty());
                            stock.setUqty(0);
                            qty = qty - stock.getUqty();
                            Date now = new Date();
                            stock.setUpdatetime(now);
                            PicktaskDetail picktaskDetail = new PicktaskDetail();
                            picktaskDetail.setPid(outorder.getId());
                            picktaskDetail.setStockid(stock.getId());
                            picktaskDetail.setCommodityid(stock.getCommodityid());
                            picktaskDetail.setCommoditybar(stock.getCommoditybar());
                            picktaskDetail.setCommodityname(stock.getCommodityname());
                            picktaskDetail.setLocatorid(stock.getLocatorid());
                            picktaskDetail.setLocatorcode(stock.getLocatorcode());
                            picktaskDetail.setLocatorname(stock.getLocatorname());
                            picktaskDetail.setQty(stock.getUqty());
                            picktaskDetailService.saveOrUpdate(picktaskDetail);
                            stockFeign.updateById(stock);
                        }
                    }
                }
            }
            outorder.setState("3");
            outorderService.updateById(outorder);
            Picktask picktask=new Picktask(); //领取人
            String token = request.getHeader("token");
            Long userid = JwtUtils.getMemberIdByJwtToken(token);
            User user = systemFeign.selectUserById(userid);
            picktask.setCreator(user.getName());
            Date now=new Date();
            picktask.setCreatetime(now);
            picktaskService.addPicktask(picktask);
            PicktaskOutorder picktaskOutorder=new PicktaskOutorder();
            picktaskOutorder.setPicktaskid(picktask.getId());
            picktaskOutorder.setOutorderid(outorder.getId());
            picktaskOutorder.setOutorderno(outorder.getOutorderno());
            picktaskOutorderService.save(picktaskOutorder);
            return R.ok().message("分配拣货").code(200);
        }else {
            return R.error().message("该订单未审核");
        }
    }

    //取消订单
    @PostMapping("cancelOutOrder/{outorderno}")
    @ApiOperation(value = "取消出库订单")
    public R cancelOutOrder(@ApiParam(value = "出库订单号")@PathVariable("outorderno") String outorderno){
        QueryWrapper<Outorder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("outorderno",outorderno);
        Outorder outorder = outorderService.getOne(queryWrapper);
        if(!outorder.getState().equals("5")) {
            String picktaskno = outorderService.selectPicktasknoByOutorderno(outorderno);
            List<ViewPicktask> viewPicktasks = picktaskService.selectViewPicktaskByPicktaskno(picktaskno);
            if(viewPicktasks.size()!=0){
                for (ViewPicktask viewPicktask : viewPicktasks) {
                    String commoditybar = viewPicktask.getCommoditybar();
                    String locatorcode = viewPicktask.getLocatorcode();
                    Integer qty = viewPicktask.getQty();
                    Stock stock = stockFeign.selectStockByComBarOriLo(commoditybar, locatorcode, 41L);
                    stock.setLqty(stock.getLqty() - qty);
                    stock.setUqty(stock.getUqty() + qty);
                    stockFeign.updateById(stock);
                    /*Long pid = outorder.getId();
                    QueryWrapper<PicktaskDetail> queryWrapper2=new QueryWrapper<>();
                    queryWrapper2.eq("pid",pid);
                    picktaskDetailService.remove(queryWrapper2);*/
                }
            }
            outorder.setState("9");
            outorderService.updateById(outorder);
            return R.ok().message("取消成功").code(200);
        }else {
            return R.error().message("该订单已出库");
        }
    }

    /*查询所有省*/
    @ApiOperation("findAllSheng")
    @PostMapping("findAllSheng")
    public List<Map> findAllSheng(){
        return outorderService.findAllSheng();
    }
    /*根据省id查询所有市区*/
    @ApiOperation("findAllShiById")
    @PostMapping("findAllShiById/{cityname}")
    public List<Map> findAllShiById(@PathVariable("cityname") String cityname){
        return outorderService.findAllShiById(cityname);
    }
    /*根据市id查询所有县*/
    @ApiOperation("findAllXianById")
    @PostMapping("findAllXianById/{cityname}")
    public List<Map> findAllXianById(@PathVariable("cityname") String cityname){
        return outorderService.findAllXianById(cityname);
    }
}

